package com.fengyi.library.controller;

import com.fengyi.library.model.Loan;
import com.fengyi.library.model.Role;
import com.fengyi.library.model.User;
import com.fengyi.library.repository.RoleRepository;
import com.fengyi.library.service.LoanService;
import com.fengyi.library.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.util.List;

@Controller
public class UserController {

    private final UserService userService;
    private final LoanService loanService;
    private final RoleRepository roleRepository;

    @Autowired
    public UserController(UserService userService, LoanService loanService, RoleRepository roleRepository) {
        this.userService = userService;
        this.loanService = loanService;
        this.roleRepository = roleRepository;
    }

    @GetMapping("/register")
    public String showRegistrationForm(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @PostMapping("/register")
    public String registerUser(@Valid @ModelAttribute("user") User user, 
                              BindingResult result, 
                              RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            return "register";
        }

        try {
            userService.registerNewStudent(user);
            redirectAttributes.addFlashAttribute("success", "注册成功，请登录");
            return "redirect:/login";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            return "redirect:/register";
        }
    }

    @GetMapping("/profile")
    public String showProfile(Model model) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User user = userService.findByUsername(auth.getName());
        model.addAttribute("user", user);
        
        // 获取用户当前借阅的图书
        List<Loan> currentLoans = loanService.findCurrentLoansByUser(user);
        model.addAttribute("currentLoans", currentLoans);
        model.addAttribute("currentLoansCount", currentLoans.size());
        
        // 获取已归还借阅数量
        List<Loan> returnedLoans = loanService.findReturnedLoansByUser(user);
        model.addAttribute("totalReturnedCount", returnedLoans.size());
        
        // 获取逾期借阅数量
        List<Loan> overdueLoans = loanService.findOverdueLoansByUser(user);
        model.addAttribute("overdueCount", overdueLoans.size());
        
        // 获取用户借阅历史
        model.addAttribute("loanHistory", loanService.findLoansByUser(
                user, PageRequest.of(0, 10, Sort.by(Sort.Direction.DESC, "borrowDate"))
        ).getContent());
        
        return "users/profile";
    }
    
    @GetMapping("/profile/edit")
    public String showEditProfileForm(Model model) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User user = userService.findByUsername(auth.getName());
        model.addAttribute("user", user);
        return "users/edit-profile";
    }
    
    @PostMapping("/profile/update")
    public String updateProfile(@Valid @ModelAttribute("user") User user, 
                              BindingResult result, 
                              RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            return "users/edit-profile";
        }
        
        try {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            User currentUser = userService.findByUsername(auth.getName());
            
            // 只允许修改姓名和邮箱
            currentUser.setName(user.getName());
            currentUser.setEmail(user.getEmail());
            
            userService.saveUser(currentUser);
            redirectAttributes.addFlashAttribute("success", "个人资料已更新");
            return "redirect:/profile";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            return "redirect:/profile/edit";
        }
    }

    @GetMapping("/admin/users")
    public String listUsers(Model model) {
        List<User> allUsers = userService.findAllUsers();
        model.addAttribute("users", allUsers);
        
        // 添加用户统计数据
        model.addAttribute("totalUsers", allUsers.size());
        model.addAttribute("studentCount", allUsers.stream()
                .filter(User::isStudent)
                .count());
        model.addAttribute("adminCount", allUsers.stream()
                .filter(User::isAdmin)
                .count());
        
        // 添加分页信息（当前未实际分页，仅为模板提供变量）
        model.addAttribute("currentPage", 0);
        model.addAttribute("totalPages", 1);
        
        return "admin/users";
    }

    @GetMapping("/admin/users/view/{id}")
    public String viewUser(@PathVariable Integer id, Model model) {
        User user = userService.findById(id);
        model.addAttribute("user", user);
        model.addAttribute("loans", loanService.findLoansByUser(
                user, PageRequest.of(0, 20, Sort.by(Sort.Direction.DESC, "borrowDate"))
        ).getContent());
        return "admin/user-detail";
    }
    
    @GetMapping("/admin/users/add")
    public String showAddUserForm(Model model) {
        model.addAttribute("user", new User());
        model.addAttribute("roles", roleRepository.findAll());
        return "admin/user-form";
    }
    
    @PostMapping("/admin/users/add")
    public String addUser(@Valid @ModelAttribute("user") User user, 
                         @RequestParam("roleId") Integer roleId,
                         BindingResult result, 
                         RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            return "admin/user-form";
        }
        
        try {
            // 根据roleId设置用户角色
            Role role = roleId == 1 ? 
                    roleRepository.findByName("ROLE_ADMIN").orElseThrow() : 
                    roleRepository.findByName("ROLE_STUDENT").orElseThrow();
            user.setRole(role);
            
            userService.saveUser(user);
            redirectAttributes.addFlashAttribute("success", "用户添加成功");
            return "redirect:/admin/users";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            return "redirect:/admin/users/add";
        }
    }

    @PostMapping("/admin/users/{id}/delete")
    public String deleteUser(@PathVariable Integer id, RedirectAttributes redirectAttributes) {
        try {
            userService.deleteUser(id);
            redirectAttributes.addFlashAttribute("success", "用户已删除");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "删除用户失败: " + e.getMessage());
        }
        return "redirect:/admin/users";
    }
    
    /**
     * 切换用户状态（启用/禁用）
     */
    @PostMapping("/admin/users/toggle-status/{id}")
    public String toggleUserStatus(@PathVariable Integer id, RedirectAttributes redirectAttributes) {
        try {
            User user = userService.findById(id);
            user.setEnabled(!user.isEnabled());
            userService.saveUser(user);
            
            String statusMessage = user.isEnabled() ? "用户已启用" : "用户已禁用";
            redirectAttributes.addFlashAttribute("success", statusMessage);
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "操作失败: " + e.getMessage());
        }
        return "redirect:/admin/users/view/" + id;
    }
    
    @GetMapping("/admin/users/edit/{id}")
    public String showEditUserForm(@PathVariable Integer id, Model model) {
        User user = userService.findById(id);
        model.addAttribute("user", user);
        return "admin/user-form";
    }
    
    @PostMapping("/admin/users/update/{id}")
    public String updateUser(@PathVariable Integer id, 
                           @Valid @ModelAttribute("user") User user, 
                           @RequestParam("roleId") Integer roleId,
                           BindingResult result, 
                           RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            return "admin/user-form";
        }
        
        try {
            User existingUser = userService.findById(id);
            existingUser.setName(user.getName());
            existingUser.setEmail(user.getEmail());
            
            // 根据roleId设置用户角色
            Role role = roleId == 1 ? 
                    roleRepository.findByName("ROLE_ADMIN").orElseThrow() : 
                    roleRepository.findByName("ROLE_STUDENT").orElseThrow();
            existingUser.setRole(role);
            
            userService.saveUser(existingUser);
            redirectAttributes.addFlashAttribute("success", "用户信息已更新");
            return "redirect:/admin/users";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", e.getMessage());
            return "redirect:/admin/users/edit/" + id;
        }
    }
    
    @PostMapping("/admin/users/disable/{id}")
    public String disableUser(@PathVariable Integer id, RedirectAttributes redirectAttributes) {
        try {
            // 由于User类没有enabled属性，我们暂时只返回成功消息，不做实际操作
            // 如果需要完整的禁用功能，需要在User类中添加enabled属性
            redirectAttributes.addFlashAttribute("success", "用户状态已更新");
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "更新用户状态失败: " + e.getMessage());
        }
        return "redirect:/admin/users";
    }
}
